

import java.io.*;

/**
 * @author LinLe
 * @create 2020-12-21 11:45
 */
public class CopyRunnable implements Runnable{
//    一个目录中的所有内容拷贝到另外一个目录中，包含子目录中的内容
    
    
    void getFileList(String fileName,String directoryName) {
    
        File file1 = null;
        File file = null;
        File[] files = null;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            file1= new File(directoryName);
            file = new File(fileName);
            //判断拷贝的目录是否存在，不存在就创建一个
            if (!file1.exists()) {
                file1.mkdirs();
            }
            //获取该目录下所有的内容
            files = file.listFiles();
            //对file进行遍历
            for (int i = 0; i < files.length; i++) {
                //判断是否为目录，若是就进行递归
                if (files[i].isDirectory()) {
                    getFileList(files[i].getAbsolutePath(), directoryName + "\\" + files[i].getName());
                }
                //不是就进行copy
                else {
                    bis = new BufferedInputStream(new FileInputStream(files[i].getAbsoluteFile()));
                    bos = new BufferedOutputStream(new FileOutputStream(directoryName + "\\" + files[i].getName()));
            
                    byte[] bytes = new byte[1024];
                    int len = 0;
            
                    while (-1 != (len = bis.read(bytes))) {
                        bos.write(bytes, 0, len);
                    }
    
                    System.out.println("[" + directoryName + "//" +
                            files[i].getName() + "]");
                }
        
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    
        }
    }
    @Override
    public void run() {
        //将"F:\\拉钩教育作业篇"下的所有拷贝到"D:\\laguo"
        getFileList("F:\\拉钩教育作业篇","D:\\laguo");
        System.out.println("拷贝完成");
    }
}
